﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using System.Linq;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using FunctionPoint.Services;
using FunctionPoint.ViewModels;
using FunctionPoint.Utility;
using FunctionPoint.Common;
using System.Collections.ObjectModel;
using FunctionPoint.UserControls;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Text.Editor;
using FunctionPoint.UIManagers;
using Microsoft.VisualStudio;
using EnvDTE;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Utilities;

namespace FunctionPoint
{
    [Guid("A59062AC-D467-4F28-9C41-BA8E4FBCCEDD")]

    public class FunctionPointSelectorToolWindowHost : ToolWindowPane, IVsShellPropertyEvents, IFunctionPointManagerServiceSubscriber, INotifyPropertyChanged
    {


        #region Private/Backing Variables
        private FunctionPointSelectorTreeControl _toolWindow;
        private FunctionPointSelectorToolWindowViewModel _viewModel;
        private uint cookie;
        private DTE dte;
        #endregion

        #region Constructors

        public FunctionPointSelectorToolWindowHost() :
            base(ServiceProvider.GlobalProvider)
        {
            this.Caption = "Function Explorer Selector";
            this.BitmapResourceID = 301;
            this.BitmapIndex = 2;

            _toolWindow = new FunctionPointSelectorTreeControl();

            IVsShell shellService = ServiceProvider.GlobalProvider.GetService(typeof(SVsShell)) as IVsShell;
            IFunctionPointManagerService managerService = ServiceProvider.GlobalProvider.GetService(typeof(SFunctionPointManagerService)) as IFunctionPointManagerService;

            managerService.RegisterProjectChangedSubscriber(this);

            if (shellService != null)
                ErrorHandler.ThrowOnFailure(shellService.AdviseShellPropertyChanges(this, out cookie));

            _toolWindow.DataContext = ViewModel;

            base.Content = _toolWindow;
        }


        #endregion

        #region Properties

        public FunctionPointSelectorToolWindowViewModel ViewModel
        {
            get
            {
                if (_viewModel == null)
                    _viewModel = new FunctionPointSelectorToolWindowViewModel();

                return _viewModel;
            }

        }

        private IFunctionPointManagerService _managerService;
        private IFunctionPointManagerService ManagerService
        {
            get
            {
                if (_managerService == null)
                    _managerService = ServiceProvider.GlobalProvider.GetService(typeof(SFunctionPointManagerService)) as IFunctionPointManagerService;

                return _managerService;
            }
        }


        #endregion




        #region Service Events

        public void ProjectContextChanged(object sender, TeamFoundationServerProjectContextChangedEventArgs args)
        {
            if (args != null)
            {
                if (args.TeamProject != null && !string.IsNullOrEmpty(args.TeamProject.Name))
                {

                    ViewModel.QueryHierarchy = ManagerService.QueryHierarchy;
                    ViewModel.QueryHierarchyFlat = ManagerService.FlattenedQueryHierarchy;
                }
                else
                {
                    ViewModel.QueryHierarchy = new ObservableCollection<QueryItemBase>();
                    ViewModel.QueryHierarchyFlat = new ObservableFlattenedQueryHierarchy();
                }
            }

        }

        #endregion

        #region Shell Events

        public int OnShellPropertyChange(int propid, object var)
        {
            if ((int)__VSSPROPID.VSSPROPID_Zombie == propid)
            {
                if ((bool)var == false)
                {

                    IVsShell shellService = GetService(typeof(SVsShell)) as IVsShell;

                    if (shellService != null)
                        ErrorHandler.ThrowOnFailure(shellService.UnadviseShellPropertyChanges(this.cookie));

                    this.cookie = 0;

                }

            }
            return VSConstants.S_OK;
        }

        #endregion

        public event PropertyChangedEventHandler PropertyChanged;


        public void RefreshQueryandRepaint(object sender, EventArgs e)
        {

            // get the current selected query so we can reselect it. 

            var currentQuery = ViewModel.SelectedQuery;
            
            ViewModel.QueryHierarchy = ManagerService.QueryHierarchy;

            ViewModel.QueryHierarchyFlat = ManagerService.FlattenedQueryHierarchy;

            if (currentQuery != null)
            {
                var newQuery = ViewModel.QueryHierarchyFlat.Where(o => o.ItemType == QueryItemType.Query)
                                    .Cast<WorkItemQuery>()
                                    .FirstOrDefault(p => p.QueryId == currentQuery.QueryId);
                
                ViewModel.SelectedQuery = newQuery; // may not be needed

            }

        }


        public void SelectedWorkItemsChanged(object sender, EventArgs e)
        {

        }

        public void WorkItemAdded(object sender, WorkItemAddedEventArgs e)
        {
            RefreshQueryandRepaint(sender, e);
        }
    }
}